package com.example.dy.pay.service.impl;

import com.example.dy.pay.domain.PaymentInfo;
import com.example.dy.pay.service.BasePayService;
import com.example.dy.pay.service.BasePayServiceManager;
import lombok.extern.slf4j.Slf4j;
import org.example.dayu521.OrderState;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Service
@Slf4j
@Primary
public class BasePayServiceImpl implements BasePayServiceManager , BasePayService {

//    private static Map<String,Function<PaymentInfo,Boolean>> svcs=new ConcurrentHashMap<>();
    private static Map<String,BasePayService> svcs=new ConcurrentHashMap<>();

    @Override
    public OrderState close_order(PaymentInfo paymentInfo) {
        var xd=svcs.get(paymentInfo.getPayment_type());
        if(xd==null){
            throw new RuntimeException("没有此服务,请检查配置");
        }
        return xd.close_order(paymentInfo);
    }

    @Override
    public boolean add_base_pay_service(String svc_name, BasePayService basePayService) {
        var pre_val = svcs.put(svc_name, basePayService);
        if(pre_val!=null){
            log.warn(STR."已经存在服务 \{svc_name}");
            return false;
        }
        return true;
    }


    @Override
    public OrderState poll_trade(PaymentInfo paymentInfo) {
        var xd=svcs.get(paymentInfo.getPayment_type());
        if(xd==null){
            throw new RuntimeException("没有此服务,请检查配置");
        }
        return xd.poll_trade(paymentInfo);
    }

    @Override
    public void refund(String order,String svc) {

        if(svc.equals("all")){
            svcs.forEach((a,s)->{
                s.refund(order,svc);
            });
            return ;
        }

        var xd=svcs.get(svc);
        if(xd==null){
            throw new RuntimeException("没有此服务,请检查配置");
        }
        xd.refund(order,svc);
    }

    @Override
    public PayAck<?> pay(Map<String,String> p, String svc) {
        var xd=svcs.get(svc);
        if(xd==null){
            throw new RuntimeException("没有此服务,请检查配置");
        }
        return xd.pay(p,svc);
    }
}
